﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.Mvc;
using Monocle.Controllers.StaticHelpers;
using Monocle.DataModel;
using Monocle.DataProvider;
using Monocle.Models;
using Monocle.Models.Facebook;

namespace Monocle.Controllers
{
    [Authorize]
    public class PageItemController : Controller
    {
        public ViewResult Edit(Guid id, IDataProvider dataProvider)
        {
            var dto = dataProvider.GetPageItemWithModule(id);
            if (dto.tFacebook != null)
            {
                var viewModel = new FacebookViewModel(dto.tFacebook);
                viewModel.Published = dto.tPageItem.Published;
                viewModel.PageItemName = dto.tPageItem.Name;
                viewModel.FK_tPage = dto.tPageItem.FK_tPage;
                viewModel = SetupFacebookViewModel(viewModel);
                return View("EditFacebook", viewModel);
            }
            if (dto.tHTML != null)
            {
                var viewModel = new HTMLViewModel(dto.tHTML);
                viewModel.Published = dto.tPageItem.Published;
                viewModel.PageItemName = dto.tPageItem.Name;
                viewModel.FK_tPage = dto.tPageItem.FK_tPage;
                viewModel.App_URL = System.Web.Configuration.WebConfigurationManager.AppSettings["App_URL"];

                return View("EditHTML", viewModel);
            }

            throw new ArgumentOutOfRangeException();
        }

        public ActionResult Delete(Guid id, IDataProvider dataProvider)
        {
            var dto = dataProvider.GetPageItem(id);

            dataProvider.DeletePageItem(dto);
            return RedirectToAction("Edit", "Page", new { id = dto.FK_tPage });
        }

        public ViewResult Create(Guid id, IDataProvider dataProvider)
        {
            //Verify the user is allowed to do this
            var parent = dataProvider.GetPage(id);

            var viewModel = new PageItemViewModel();
            viewModel.FK_tPage = id;

            return View("Create", viewModel);
        }

        [HttpPost]
        public ActionResult Create(PageItemViewModel viewModel, IDataProvider dataProvider)
        {
            if (!ModelState.IsValid)
            {
                //The viewmodel is not valid. Return input and the view
                return View(viewModel);
            }
            else
            {
                try
                {
                    //Save the site to the database
                    viewModel.FK_tPage = viewModel.FK_tPage;
                    viewModel.ID = Guid.NewGuid();
                    dataProvider.SavePageItem(viewModel.ToDTO());

                    switch ((Models.Enums.Modules)viewModel.SelectedModule)
                    {
                        case Models.Enums.Modules.HTMLModule:
                            var hdto = new tHTML();
                            hdto.PK_tHTML = Guid.NewGuid();
                            hdto.FK_tPageItem = viewModel.ID;
                            hdto = dataProvider.SaveHTMLModule(hdto);
                            var vm = new HTMLViewModel(hdto);
                            vm.Published = false;
                            vm.PageItemName = viewModel.Name;
                            return View("EditHTML", vm);

                        case Models.Enums.Modules.FacebookModule:
                            var fdto = new tFacebook();
                            fdto.PK_tFacebook = Guid.NewGuid();
                            fdto.FK_tPageItem = viewModel.ID;
                            fdto.Limit = 10;
                            fdto.ContentType = "feed";
                            fdto.Name = "";
                            fdto = dataProvider.SaveFacebookModule(fdto);
                            var fvm = new FacebookViewModel(fdto);
                            fvm.Published = false;
                            fvm.PageItemName = viewModel.Name;
                            return View("CreateFacebook", fvm);
                    }

                }
                catch (Exception e)
                {
                    //        If an error happens add that to the modelstate and return view
                    ModelState.AddModelError("", "En fejl er opstået: " + e.Message);
                    return View(viewModel);
                }

                //Redirect the user to somewhere else. Could be a success page
                return RedirectToAction("Edit", "Page", new { id = viewModel.FK_tPage });
            }
        }

        [HttpPost]
        [ValidateInput(false)]
        public ActionResult SaveHTML(HTMLViewModel viewModel, IDataProvider dataProvider)
        {
            if (!ModelState.IsValid)
            {
                //The viewmodel is not valid. Return input and the view
                return View("EditHTML", viewModel);
            }
            else
            {
                //Get the old DTO from the database
                var dbDTO = dataProvider.GetHTMLModule(viewModel.ModuleID);

                //Merge it with the new (update fields)
                UpdateModel(dbDTO);
                try
                {
                    //Save the site to the database
                    viewModel.UpdateFromDTO(dataProvider.SaveHTMLModule(dbDTO));
                }
                catch (Exception e)
                {
                    //        If an error happens add that to the modelstate and return view
                    ModelState.AddModelError("", "En fejl er opstået: " + e.Message);
                    return View("EditHTML", viewModel);
                }

                var pageItem = dataProvider.GetPageItem(dbDTO.FK_tPageItem);
                try
                {
                    pageItem.Published = viewModel.Published;
                    pageItem.Name = viewModel.PageItemName;
                    dataProvider.SavePageItem(pageItem);
                }
                catch (Exception e)
                {
                    //        If an error happens add that to the modelstate and return view
                    ModelState.AddModelError("", "En fejl er opstået: " + e.Message);
                    return View("EditHTML", viewModel);
                }

                //Redirect the user to somewhere else. Could be a success page
                ViewBag.Status = Monocle.Resources.Monocle.Generic_Saved;
                viewModel.App_URL = System.Web.Configuration.WebConfigurationManager.AppSettings["App_URL"];
                return View("EditHTML", viewModel);
            }

        }

        [HttpPost]
        public ActionResult CreateFacebook(FacebookViewModel viewModel, IDataProvider dataProvider)
        {
            if (!ModelState.IsValid)
            {
                //The viewmodel is not valid. Return input and the view
                return View("CreateFacebook", viewModel);
            }
            else
            {
                //Verify the pageName
                if (Facebook.VerifyPageName(viewModel.PageName, viewModel))
                {
                    //Get the old DTO from the database
                    var dbDTO = dataProvider.GetFacebookModule(viewModel.ModuleID);

                    //Merge it with the new (update fields)
                    UpdateModel(dbDTO);
                    try
                    {
                        //    Save the site to the database
                        dataProvider.SaveFacebookModule(dbDTO);
                    }
                    catch (Exception e)
                    {
                        //If an error happens add that to the modelstate and return view
                        ModelState.AddModelError("", "En fejl er opstået: " + e.Message);
                        return View("CreateFacebook", viewModel);
                    }
                    viewModel = SetupFacebookViewModel(viewModel);
                    return View("EditFacebook", viewModel);
                }
                else
                {

                    ModelState.AddModelError("PageName", Monocle.Resources.Monocle.Module_Facebook_PageName_Invalid);
                    return View("CreateFacebook", viewModel);
                }
            }

        }

        [HttpPost]
        public ActionResult SaveFacebook(FacebookViewModel viewModel, IDataProvider dataProvider)
        {
            if (!ModelState.IsValid)
            {
                //The viewmodel is not valid. Return input and the view
                return View("EditFacebook", viewModel);
            }
            else
            {
                if (Facebook.VerifyPageName(viewModel.PageName, viewModel))
                {
                    //Get the old DTO from the database
                    var dbDTO = dataProvider.GetFacebookModule(viewModel.ModuleID);

                    //Merge it with the new (update fields)
                    UpdateModel(dbDTO);
                    try
                    {
                        //    Save the site to the database
                        viewModel.UpdateFromDTO(dataProvider.SaveFacebookModule(dbDTO));
                    }
                    catch (Exception e)
                    {
                        //        If an error happens add that to the modelstate and return view
                        viewModel = SetupFacebookViewModel(viewModel);
                        ModelState.AddModelError("", "En fejl er opstået: " + e.Message);
                        return View("EditFacebook", viewModel);
                    }

                    var pageItem = dataProvider.GetPageItem(dbDTO.FK_tPageItem);
                    try
                    {
                        pageItem.Published = viewModel.Published;
                        pageItem.Name = viewModel.PageItemName;
                        dataProvider.SavePageItem(pageItem);
                    }
                    catch (Exception e)
                    {
                        //        If an error happens add that to the modelstate and return view
                        viewModel = SetupFacebookViewModel(viewModel);
                        ModelState.AddModelError("", "En fejl er opstået: " + e.Message);
                        return View("EditFacebook", viewModel);
                    }

                    ViewBag.Status = Monocle.Resources.Monocle.Generic_Saved;
                    viewModel = SetupFacebookViewModel(viewModel);
                    return View("EditFacebook", viewModel);
                }
                else
                {
                    ModelState.AddModelError("PageName", Monocle.Resources.Monocle.Module_Facebook_PageName_Invalid);
                    viewModel = SetupFacebookViewModel(viewModel);
                    return View("EditFacebook", viewModel);
                }
            }

        }

        public FacebookViewModel SetupFacebookViewModel(FacebookViewModel viewModel)
        {
            var appID = "";
            var appSecret = ""; //TODO: Fetch from config file
            var AuthToken = WebStream.GetWebStream("https://graph.facebook.com/oauth/access_token?grant_type=client_credentials&client_id=" + appID + "&client_secret=" + appSecret);
            var stream = WebStream.GetWebStream("https://graph.facebook.com/" + viewModel.PageName + "/albums?" + AuthToken);
            viewModel.GalleryList = FacebookGallery.GetGalleryList(stream);
            return viewModel;
        }
    }
}
